﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Task.DownloadImage.Utilities
{
    public class DoownloadHelper
    {
        public static Bitmap WebDownloadAsync(string uri,string targetPath, DownloadProgressChangedEventHandler client_DownloadProgressChanged)
        {
            WebClient client = new WebClient();
            if (client_DownloadProgressChanged != null)
            {
                client.DownloadProgressChanged += client_DownloadProgressChanged; 
            }
            client.DownloadFile(new Uri(uri), targetPath);
            var rawImg =  new Bitmap(targetPath);
            var resizeImg = resizeImage(rawImg,new Size(160,120));
            return (Bitmap)resizeImg;
        }

        private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
        {
            //获取图片宽度
            int sourceWidth = imgToResize.Width;
            //获取图片高度
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            //计算宽度的缩放比例
            nPercentW = ((float)size.Width / (float)sourceWidth);
            //计算高度的缩放比例
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            //期望的宽度
            int destWidth = (int)(sourceWidth * nPercent);
            //期望的高度
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //绘制图像
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            return (System.Drawing.Image)b;
        }
    }
}
